package com.zly.mybatisdemo.token;

//import com.zly.mybatisdemo.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.zly.mybatisdemo.utils.RedisClient;
import com.zly.mybatisdemo.token.TokenModel;
import com.zly.mybatisdemo.token.TokenHelper;
import com.zly.mybatisdemo.utils.SecurityConstant;
import com.zly.mybatisdemo.config.TokenConfig;
import com.zly.mybatisdemo.utils.TokenUtils;

import java.util.Timer;
import java.util.UUID;

/**
 * @ClassName RedisTokenHelp
 * @Author zhaokang
 * @Description TODO
 * @Date 2021/1/21 14:18
 */
@Slf4j
@Component
public class RedisTokenHelp implements TokenHelper {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private TokenConfig tokenConfig;

    @Override
    public TokenModel create(String userId, String userName) {
        Long currentTimeMillis = System.currentTimeMillis();
        String strCurrentTimeMillis = String.valueOf(currentTimeMillis);
        String token = TokenUtils.getToken(userId, userName);
        TokenModel model = new TokenModel(userId, token, userName);
        redisClient.set(userId, token, tokenConfig.getTokenExpireTime());
        return model;
    }

    @Override
    public boolean check(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        //取出token包含的身份
        String userId = TokenUtils.getClaim(token, SecurityConstant.USER_ID);
        if (StringUtils.isEmpty(userId)) {
            log.error(String.format("认证失败，未解析出userId，token=%s", token));
            return false;
        }
        String authenticatedToken = redisClient.get(userId);
        if (!token.equals(authenticatedToken)) {
            log.error(String.format("认证失败，token不匹配，token=%s，userId=%s", token, userId));
            return false;
        }
        redisClient.expire(userId, tokenConfig.getTokenExpireTime());
        return true;
    }

    @Override
    public boolean delete(String userId) {
        return redisClient.remove(userId);
    }
}
